public class CirDoublyList<T> extends Object{
    Node<T> head;
    Node<T> last;
    public CirDoublyList(){
        this.head = new Node<>();
        this.head.prev = this.head;
        this.head.next = this.head;
        last = head;
    }


    @Override
    public String toString() {
        String str = "";
        Node<T> cur = this.head.next;
        while(cur != this.last){
            str += cur.val+" ";
            cur = cur.next;
        }
        return str;
    }
    public void insert(T x){
        Node<T> node = new Node<>(x,last,last.next);
        last.prev.next = node;
        node.prev = last.prev;
        last.prev = node;
        node.next = last;
    }

    public void concat(CirDoublyList<T> list){
        if (list.head.next == list.last) return;
        this.last.prev.next = list.head.next;
        list.head.next.prev = this.last.prev;
        list.last.next = this.head;
        this.head.prev = list.last;
        this.last = list.last;
        list = null;
    }

    public static void main(String[] args) {
        CirDoublyList<String> cirDoublyList = new CirDoublyList<>();
        for (int i = 0; i < 10; i++) {
            cirDoublyList.insert(i+"");
        }
        System.out.println("初识循环链表：" + cirDoublyList.toString());

        CirDoublyList<String> a = new CirDoublyList<>();
        for (int i = 10; i < 20; i++) {
            a.insert(i+"");
        }
        System.out.println("被合并的循环链表：" + a.toString());

        cirDoublyList.concat(a);
        System.out.println("合并后：" + cirDoublyList.toString());
    }
}
